package com.example.administrator.about_huanxin.presenter.activity;

import android.util.Log;

import com.example.administrator.about_huanxin.SimpelEmCallBack;
import com.example.administrator.about_huanxin.model.UserEntity;
import com.example.administrator.about_huanxin.view.activity.LoginActivityView;
import com.hyphenate.chat.EMClient;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by Administrator on 2017/3/21 0021.
 */

public class LoginPresenterImp implements LoginPresenter {

    private LoginActivityView loginActivityView;

    public LoginPresenterImp(LoginActivityView loginActivityView) {
        this.loginActivityView = loginActivityView;
    }

    @Override
    public void login(final String user, final String pwd) {
        Log.e("login", user + "..." + pwd);
        EMClient.getInstance().login(user, pwd, new SimpelEmCallBack() {
            @Override
            public void onSuccess() {
                super.onSuccess();
                loginActivityView.afterLogin(true);

                //两个方法是为了保证进入主页面后本地会话和群组都 load 完毕。
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();

                getUserInfo(user,pwd);
            }

            @Override
            public void onError(int i, String s) {
                super.onError(i, s);
                Log.e("loginerror", i + "..." + s);
                loginActivityView.afterLogin(false);
                EMClient.getInstance().logout(true);
            }
        });
    }

    //根据传入的用户名密码查找人员信息
    private void getUserInfo(String user, String pwd) {
        BmobQuery<UserEntity> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("username", user)
                .addWhereEqualTo("password", pwd)
                .findObjects(new FindListener<UserEntity>() {
                    @Override
                    public void done(List<UserEntity> list, BmobException e) {
                        if (list.size() != 0 && e == null) {
                            UserEntity userEntity = list.get(0);
                            loginActivityView.getUserInfo(userEntity);
                        }
                    }
                });
    }

}
